<template>
  <div class="profile-editor">
    <el-form ref="formRef" :model="formData" :rules="formRules" @submit.prevent>
      <el-form-item label="标题" prop="title">
        <el-input
          class="title-ipt"
          v-model="formData.title"
          type="text"
          autocomplete="off"
          placeholder="请填写标题"
        />
      </el-form-item>

      <el-form-item label="简介" prop="intro">
        <el-input
          class="intro-ipt"
          v-model="formData.intro"
          type="textarea"
          maxlength="300"
          placeholder="请填写文章简介"
          show-word-limit
          autocomplete="off"
          resize="none"
          :autosize="{ minRows: 7 }"
        />
      </el-form-item>

      <el-form-item label="正文" prop="content">
        <div class="my-editor">
          <mavon-editor
            :class="{ 'm-editor': !isMEditorFullscreen }"
            ref="editorRef"
            v-model="formData.content"
            @imgAdd="handleImgAdd"
          />
        </div>
      </el-form-item>

      <el-form-item label="添加标签" prop="labelsSelect">
        <div class="check-box">
          <el-checkbox-group v-model="formData.labelsSelect" size="large">
            <el-checkbox-button v-for="tag in labelsFixed" :key="tag" :label="tag">
              <div class="label-box">
                <span>{{ tag }}</span>
              </div>
            </el-checkbox-button>
            <el-checkbox-button v-for="tag in labels" :key="tag" :label="tag">
              <div class="label-box">
                <span>{{ tag }}</span>
                <el-icon
                  v-show="!formData.labelsSelect.includes(tag)"
                  class="del-label"
                  @click.stop="handleDelLabel(tag)"
                >
                  <Close />
                </el-icon>
              </div>
            </el-checkbox-button>
          </el-checkbox-group>

          <div class="tip-box" v-if="labels.length < 4">
            <el-input
              class="label-ipt"
              v-if="isShowIpt"
              ref="InputRef"
              v-model="labelVal"
              size="small"
              @keyup.enter="handleInputConfirm"
              @blur="handleInputConfirm"
              maxlength="24"
            />
            <el-icon v-if="!isShowIpt" class="add" color="#0075FF" @click="showInput"
              ><Plus
            /></el-icon>

            <span class="tip">最多4个，建议为行业分类</span>
          </div>
        </div>
      </el-form-item>

      <el-form-item label=" " prop="agree">
        <div class="agree">
          <el-checkbox v-model="isAgree" size="large">
            <span>阅读并同意</span>
          </el-checkbox>
          <span class="disclaimers" @click.stop="handleDisclaimers">免责声明</span>
        </div>
      </el-form-item>

      <el-form-item label=" ">
        <div
          class="action hover-half"
          @click.stop="handleSubmit('edit')"
          v-if="route.query.articleId"
        >
          保存修改
        </div>
        <div v-else class="action hover-half" @click.stop="handleSubmit('add')">发布文章</div>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import useRouterJump from '@/hooks/useRouterJump'
import useProfileStore from '@/stores/profile/profile'
import { ElMessage } from 'element-plus'
import { storeToRefs } from 'pinia'
import { ref, nextTick, computed, watch } from 'vue'
import { useRoute } from 'vue-router'

// ====== route、store
const route = useRoute()
const profileStore = useProfileStore()
const { isEditArticle } = storeToRefs(profileStore)

// ====== data
const editorRef = ref<any>()
const InputRef = ref<any>()
const formRef = ref<any>()
const formData = ref<any>({
  title: '',
  intro: '',
  content: '',
  labelsSelect: []
})
const formRules = ref<any>({
  title: [{ required: true, message: '请填写标题', trigger: 'submit' }],
  intro: [{ required: true, message: '请填写文章简介', trigger: 'submit' }],
  content: [{ required: true, message: '请填写正文', trigger: 'submit' }],
  labelsSelect: [{ required: true, message: '请选择至少一条标签', trigger: 'submit' }]
})
const labelsFixed = ref<string[]>([]) // 固定的
const labels = ref<string[]>([]) // 新增的
const labelVal = ref<any>('')
const isShowIpt = ref<boolean>(false)
const isAgree = ref<boolean>(false)
const isMEditorFullscreen = computed(() => editorRef.value?.s_fullScreen ?? false)

// ====== watch
watch(
  () => route.query,
  () => {
    if (!route.query.editorId) {
      formData.value.title = ''
      formData.value.intro = ''
      formData.value.labelsSelect = []
      formData.value.content = ''
    }
  }
)

// ====== methods
const showInput = () => {
  isShowIpt.value = true
  nextTick(() => {
    InputRef.value!.input!.focus()
  })
}
const handleInputConfirm = () => {
  if (labelVal.value && labels.value.findIndex(item => item == labelVal.value) === -1) {
    labels.value.push(labelVal.value)
    formData.value.labelsSelect.push(labelVal.value)
  }
  isShowIpt.value = false
  labelVal.value = ''
}
const handleDisclaimers = () => {
  console.log(editorRef.value)
}
const handleImgAdd = (filename: string, file: File) => {
  const fd = new FormData()
  fd.append('image', file)
  profileStore.uploadImageAction(fd, res => {
    editorRef.value?.$img2Url(filename, res.result)
  })
}
const handleSubmit = (type: 'edit' | 'add') => {
  formRef.value?.validate((valid: boolean) => {
    if (valid) {
      if (isAgree.value) {
        if (type === 'add') {
          profileStore.uploadPublishAction(
            {
              title: formData.value.title,
              introduction: formData.value.intro,
              arrayParam: formData.value.labelsSelect,
              file_url: formData.value.content
            },
            () => {
              isEditArticle.value = false
            }
          )
        } else {
          profileStore.uploadPublishAction(
            {
              id: String(route.query.articleId),
              title: formData.value.title,
              introduction: formData.value.intro,
              arrayParam: formData.value.labelsSelect,
              file_url: formData.value.content
            },
            () => {
              isEditArticle.value = false
              useRouterJump('/article-detail', { articleId: route.query.articleId })
            }
          )
        }
      } else {
        ElMessage({
          message: '请仔细阅读并勾选免责声明',
          type: 'warning'
        })
      }
    } else {
      return false
    }
  })
}
const handleDelLabel = (tag: string) => {
  let index: number | null = labels.value.findIndex(item => item === tag)
  if (index !== -1) {
    labels.value.splice(index, 1)
  }
  index = null
}

// ====== tool
function setupInit() {
  // 获取固定label
  profileStore.preSelectListAction((res: any) => {
    if (res.result?.length > 0) {
      labelsFixed.value = res.result[0]?.names.map((item: any) => item.name)
    }
  })

  // 是否为编辑模式
  if (route.query.articleId) {
    // 编辑模式回显处理
    profileStore.articleDisplayAction(
      {
        file_id: String(route.query.articleId),
        display_state: 1
      },
      res => {
        const { title, introduction, label, file_url } = res.result
        formData.value.title = title ?? ''
        formData.value.intro = introduction ?? ''
        formData.value.labelsSelect = label ?? []
        formData.value.content = file_url ?? ''

        if (label && label.length > 0) {
          for (const item of label) {
            if (!labelsFixed.value.includes(item)) {
              labels.value.push(item)
            }
          }
        }
      }
    )
  }
}

// ====== lifecycle
setupInit()
</script>

<style lang="less" scoped>
.profile-editor {
  :deep(.el-form-item) {
    margin-bottom: 60px;

    .el-form-item__label {
      width: 120px;
      font-size: 20px;
      justify-content: flex-start;
    }

    .title-ipt {
      font-size: 20px;
      border-bottom: 1px solid #d6d6d6;

      .el-input__wrapper {
        box-shadow: none;
      }
    }

    .intro-ipt {
      font-size: 18px;
    }
  }
  :deep(.el-form-item:nth-of-type(4)),
  :deep(.el-form-item:nth-of-type(5)) {
    margin-bottom: 40px;
  }

  .my-editor {
    width: 100%;
    border: 1px solid #d6d6d6;

    .m-editor {
      height: 800px;
      z-index: 1499;
    }
  }

  :deep(.check-box) {
    .label-box {
      display: flex;
      align-items: center;

      .del-label {
        font-size: 14px;
        border-radius: 50%;
        box-sizing: content-box;
        transition: all 0.3s ease;
        color: #000000;
        margin-left: 10px;
      }
    }
    .el-checkbox-button {
      margin: 0 10px 10px 0;

      .el-checkbox-button__inner {
        border: 1px solid #cccccc;
      }
    }
    .el-checkbox-button:hover .del-label {
      color: #0075ff;
    }

    .tip-box {
      display: flex;
      align-items: center;
      height: 40px;

      .label-ipt {
        width: 200px;
        height: 35px;
      }
      .add {
        flex-grow: 0;
        font-size: 18px;
        cursor: pointer;
      }
      .tip {
        display: flex;
        justify-content: center;
        align-items: center;
        font-size: 16px;
        color: #aaaaaa;
        margin-left: 19px;
        white-space: nowrap;
      }
    }
  }

  :deep(.agree) {
    display: flex;
    align-items: center;

    .el-checkbox__input.is-checked + .el-checkbox__label {
      color: #999999;
    }
    .el-checkbox__inner {
      width: 21px;
      height: 21px;
    }
    .el-checkbox__inner::after {
      width: 6px;
      height: 12px;
      left: 6px;
    }
    .el-checkbox__label {
      font-size: 17px;
    }
    .disclaimers {
      font-size: 17px;
      color: #0075ff;
      transform: translateY(-1px);
      cursor: pointer;
    }
  }
  .action {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 150px;
    height: 50px;
    border: none;
    background: #0075ff;
    box-shadow: 0px 3px 3px 0px rgba(0, 0, 0, 0.1);
    border-radius: 7px;
    font-size: 21px;
    color: #ffffff;
  }
}
</style>
